package spotGUI.eventsGUI;

import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.IOException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.Calendar;

import javax.swing.Box;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import managers.DBManager;
import managers.EventsManager;
import personalProfile.PersonalProfile;
import utils.SocialUserData;
import utils.StackTracePrinter;

import com.toedter.calendar.JDateChooser;

import elements.Event;
import java.util.ResourceBundle;

public class EventsFrame extends JFrame {

	protected static final int FIXED_CELL_WIDTH = 220;


	private JDateChooser dateChooserFrom;
	private JDateChooser dateChooserTo;
	private JLabel lblBox1;
	private JLabel lblBox2;
	private JButton btnSearch;
	private JButton btnReset;
	private JLabel lblBirthday;
	private JLabel lblTitle;
	private Box boxSelectPeriod;
	private Component horizontalStrut;
	private Component horizontalStrut_1;
	private Component horizontalStrut_2;
	private Component horizontalStrut_3;
	private JList listBirthday;
	private Component horizontalStrut_4;
	private EventViewer eventViewer;
	private JList listEvents;
	private JLabel lblEvents;
	private Font font = new Font("Agency FB", Font.BOLD, 22);

	private EventsManager manager;
	private JLabel lblWarning;
	private Component horizontalStrut_5;

	private JPanel panel = new JPanel();
	private JScrollPane scrollPane;

	public EventsFrame(final EventsManager manager) {
		
		this.manager = manager;
		
		setTitle(ResourceBundle.getBundle("spotGUI.eventsGUI.messages").getString("EventsFrame.this.title")); //$NON-NLS-1$ //$NON-NLS-2$
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setMinimumSize(new Dimension(730, 580));
		setSize(new Dimension(730, 560));
		setLocationRelativeTo(null);
		setIconImage(Toolkit.getDefaultToolkit().getImage(EventsFrame.class.getResource("/images/Icons/64x64/users_comments.png")));
		
		setContentPane(panel);
		
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{696, 0};
		gridBagLayout.rowHeights = new int[]{0, 0, 25, 50, 0, 70, 0, 0};
		gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
		panel.setLayout(gridBagLayout);
		panel.setBorder(new EmptyBorder(0, 10, 10, 10));

		lblTitle = new JLabel("");
		lblTitle.setIcon(new ImageIcon(EventsFrame.class.getResource("/images/GUIBackgrounds/eventsAndBirthdays.png")));
		lblTitle.setFont(new Font("Agency FB", Font.BOLD, 49));
		GridBagConstraints gbc_lblTitle = new GridBagConstraints();
		gbc_lblTitle.anchor = GridBagConstraints.WEST;
		gbc_lblTitle.insets = new Insets(0, 0, 5, 0);
		gbc_lblTitle.gridx = 0;
		gbc_lblTitle.gridy = 0;
		panel.add(lblTitle, gbc_lblTitle);

		boxSelectPeriod = Box.createHorizontalBox();
		GridBagConstraints gbc_boxSelectPeriod = new GridBagConstraints();
		gbc_boxSelectPeriod.anchor = GridBagConstraints.WEST;
		gbc_boxSelectPeriod.fill = GridBagConstraints.VERTICAL;
		gbc_boxSelectPeriod.insets = new Insets(0, 0, 5, 0);
		gbc_boxSelectPeriod.gridx = 0;
		gbc_boxSelectPeriod.gridy = 1;
		panel.add(boxSelectPeriod, gbc_boxSelectPeriod);

		lblBox1 = new JLabel(ResourceBundle.getBundle("spotGUI.eventsGUI.messages").getString("EventsFrame.lblBox1.text")); //$NON-NLS-1$ //$NON-NLS-2$
		boxSelectPeriod.add(lblBox1);

		horizontalStrut = Box.createHorizontalStrut(10);
		boxSelectPeriod.add(horizontalStrut);

		dateChooserFrom = new JDateChooser();
		dateChooserFrom.setMinimumSize(new Dimension(130, 21));
		boxSelectPeriod.add(dateChooserFrom);

		horizontalStrut_1 = Box.createHorizontalStrut(10);
		boxSelectPeriod.add(horizontalStrut_1);

		lblBox2 = new JLabel(ResourceBundle.getBundle("spotGUI.eventsGUI.messages").getString("EventsFrame.lblBox2.text")); //$NON-NLS-1$ //$NON-NLS-2$
		boxSelectPeriod.add(lblBox2);

		horizontalStrut_2 = Box.createHorizontalStrut(10);
		boxSelectPeriod.add(horizontalStrut_2);

		dateChooserTo = new JDateChooser();
		dateChooserTo.setMinimumSize(new Dimension(130, 21));
		dateChooserTo.getCalendarButton().setMinimumSize(new Dimension(150, 21));
		boxSelectPeriod.add(dateChooserTo);

		horizontalStrut_3 = Box.createHorizontalStrut(10);
		boxSelectPeriod.add(horizontalStrut_3);

		btnSearch = new JButton(ResourceBundle.getBundle("spotGUI.eventsGUI.messages").getString("EventsFrame.btnSearch.text")); //$NON-NLS-1$ //$NON-NLS-2$
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					manager.retrieveEvents(dateChooserFrom.getDate(), dateChooserTo.getDate(), DBManager.getConnection());
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					StackTracePrinter.print(e1);
				} catch (IllegalArgumentException e2) {
					lblWarning.setVisible(true);
				}
				validate();
			}
		});
		boxSelectPeriod.add(btnSearch);

		horizontalStrut_4 = Box.createHorizontalStrut(10);
		boxSelectPeriod.add(horizontalStrut_4);

		btnReset = new JButton(ResourceBundle.getBundle("spotGUI.eventsGUI.messages").getString("EventsFrame.btnReset.text")); //$NON-NLS-1$ //$NON-NLS-2$
		btnReset.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				resetEventsBox();
				try {
					manager.updateEventList(DBManager.getConnection());
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					StackTracePrinter.print(e);
				}
			}
		});
		boxSelectPeriod.add(btnReset);

		lblWarning = new JLabel("");
		lblWarning.setIcon(new ImageIcon(EventsFrame.class.getResource("/images/Icons/24x24px/warning.png")));
		lblWarning.setVisible(false);

		horizontalStrut_5 = Box.createHorizontalStrut(10);
		boxSelectPeriod.add(horizontalStrut_5);
		boxSelectPeriod.add(lblWarning);

		lblBirthday = new JLabel(ResourceBundle.getBundle("spotGUI.eventsGUI.messages").getString("EventsFrame.lblBirthday.text")); //$NON-NLS-1$ //$NON-NLS-2$
		lblBirthday.setFont(font);
		GridBagConstraints gbc_lblBirthday = new GridBagConstraints();
		gbc_lblBirthday.anchor = GridBagConstraints.NORTHWEST;
		gbc_lblBirthday.insets = new Insets(0, 0, 5, 0);
		gbc_lblBirthday.gridx = 0;
		gbc_lblBirthday.gridy = 2;
		panel.add(lblBirthday, gbc_lblBirthday);

		listBirthday = new JList();
		listBirthday.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		listBirthday.setOpaque(false);
		listBirthday.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listBirthday.addListSelectionListener(new OpenPersonalProfileSelectionListener());
		listBirthday.setModel(new DefaultListModel());
		listBirthday.setCellRenderer(new BirthdayCellRenderer());
		listBirthday.setLayoutOrientation(JList.HORIZONTAL_WRAP);
		GridBagConstraints gbc_listBirthday = new GridBagConstraints();
		gbc_listBirthday.anchor = GridBagConstraints.WEST;
		gbc_listBirthday.insets = new Insets(0, 0, 5, 0);
		gbc_listBirthday.fill = GridBagConstraints.VERTICAL;
		gbc_listBirthday.gridx = 0;
		gbc_listBirthday.gridy = 3;
		panel.add(listBirthday, gbc_listBirthday);

		lblEvents = new JLabel(ResourceBundle.getBundle("spotGUI.eventsGUI.messages").getString("EventsFrame.lblEvents.text")); //$NON-NLS-1$ //$NON-NLS-2$
		lblEvents.setFont(font);
		GridBagConstraints gbc_lblEvents = new GridBagConstraints();
		gbc_lblEvents.anchor = GridBagConstraints.NORTHWEST;
		gbc_lblEvents.insets = new Insets(0, 0, 5, 0);
		gbc_lblEvents.gridx = 0;
		gbc_lblEvents.gridy = 4;
		panel.add(lblEvents, gbc_lblEvents);
		
		scrollPane = new JScrollPane();
		scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		GridBagConstraints gbc_scrollPane = new GridBagConstraints();
		gbc_scrollPane.fill = GridBagConstraints.BOTH;
		gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
		gbc_scrollPane.gridx = 0;
		gbc_scrollPane.gridy = 5;
		panel.add(scrollPane, gbc_scrollPane);

		listEvents = new JList();
		listEvents.setVisibleRowCount(4);
		scrollPane.setViewportView(listEvents);
		listEvents.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		listEvents.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listEvents.setModel(new DefaultListModel());
		listEvents.addListSelectionListener(new EventListListener());
		listEvents.setCellRenderer(new EventsCellRenderer());
		listEvents.setOpaque(false);

		eventViewer = new EventViewer(manager);
		eventViewer.setBorder(new CompoundBorder(new EtchedBorder(EtchedBorder.RAISED, new Color(247, 231, 34), new Color(233, 199, 5)), new EmptyBorder(10, 10, 10, 10)));
		GridBagConstraints gbc_eventViewer = new GridBagConstraints();
		gbc_eventViewer.fill = GridBagConstraints.BOTH;
		gbc_eventViewer.gridx = 0;
		gbc_eventViewer.gridy = 6;
		panel.add(eventViewer, gbc_eventViewer);
		eventViewer.setVisible(true);

		addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent arg0) {
				int columnCount = getWidth() / FIXED_CELL_WIDTH;
				int rowCount = listBirthday.getModel().getSize()/columnCount;
				if (listBirthday.getModel().getSize()%columnCount != 0) {
					rowCount++;
				}
				listBirthday.setVisibleRowCount(rowCount);
			}
		});
	}





	public void addEvent (Event event) {
		((DefaultListModel)listEvents.getModel()).addElement(event);

	}

	public void removeEvents () {
		((DefaultListModel)listEvents.getModel()).removeAllElements();
	}

	public void addBirthday (Birthday birthday) {
		((DefaultListModel)listBirthday.getModel()).addElement(birthday);
	}


	private class BirthdayCellRenderer implements ListCellRenderer {

		private DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
		private ImageIcon giftIcon = new ImageIcon(EventsCellRenderer.class.getResource("/images/Icons/48x48/gift.png"));
		private ImageIcon smallGiftIcon = new ImageIcon(EventsCellRenderer.class.getResource("/images/Icons/32x32/gift.png"));

		@Override
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean cellHasFocus) {

			Birthday birthday = (Birthday) value;
			JLabel listCellRendererComponent = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
			listCellRendererComponent.setOpaque(false);

			if (birthday.getUser() == null) {
				listCellRendererComponent.setIcon(smallGiftIcon);
				listCellRendererComponent.setText(ResourceBundle.getBundle("spotGUI.eventsGUI.messages").getString("EventsFrame.1"));
				return listCellRendererComponent;
			}

			Calendar currentDate = Calendar.getInstance();
			Calendar birthDate = Calendar.getInstance();
			birthDate.setTime(birthday.getDate());
			int day = birthDate.get(Calendar.DAY_OF_MONTH);
			int month = birthDate.get(Calendar.MONTH);
			if (currentDate.get(Calendar.DAY_OF_MONTH) == day &&
					currentDate.get(Calendar.MONTH) == month) {
				listCellRendererComponent.setIcon(giftIcon);
				listCellRendererComponent.setText("<HTML><b>"+birthday.getUser().getFirstName()+" "+birthday.getUser().getSurname()+":   <i>oggi</i></b><HTML>");
			} else {
				String temp = DateFormat.getDateInstance(DateFormat.LONG).format(birthDate);
				temp.substring(0, temp.length()-5);
				
				listCellRendererComponent.setIcon(smallGiftIcon);
				listCellRendererComponent.setText("<HTML>"+birthday.getUser().getFirstName()+" "+birthday.getUser().getSurname()
						+":   <i>"+temp+"</i><HTML>");
			}


			return listCellRendererComponent;
		}

	}


	private class EventsCellRenderer implements ListCellRenderer {

		private DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
		private ImageIcon calendarIcon = new ImageIcon(EventsCellRenderer.class.getResource("/images/Icons/24x24/calendar_blank.png"));

		@Override
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean cellHasFocus) {

			Event event = (Event) value;

			JLabel listCellRendererComponent = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
			listCellRendererComponent.setOpaque(false);
			listCellRendererComponent.setIcon(calendarIcon);
			String text = "<HTML><b>"+event.name+"</b>";
			if (event.eventId != EventsManager.NO_EVENTS)
				text += "     <i>"+DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(event.date)+"</i>";
			listCellRendererComponent.setText(text);

			return listCellRendererComponent;
		}

	}


	private class OpenPersonalProfileSelectionListener implements ListSelectionListener {

		@Override
		public void valueChanged(ListSelectionEvent e) {
			if ((((JList) e.getSource()).getSelectedValue()) != null && !e.getValueIsAdjusting()) {
				SocialUserData user = ((Birthday) ((JList)(e.getSource())).getSelectedValue()).getUser();
				if (user != null)
					new PersonalProfile(user.getUserId());
				((JList)e.getSource()).clearSelection();
			}
		}
	}

	private class EventListListener implements ListSelectionListener {

		@Override
		public void valueChanged(ListSelectionEvent e) {
			if (e.getValueIsAdjusting())
				return;
			Event event = (Event) ((JList)(e.getSource())).getSelectedValue();
			if (event == null)
				return;
			try {
				if (event.eventId != EventsManager.NO_EVENTS) {
					manager.retrieveCompleteEvent(event, DBManager.getConnection());
					eventViewer.setEvent(event);
				} else
					eventViewer.setNoEvents(event);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				StackTracePrinter.print(e1);
			} catch (IOException e2) {
				// TODO Auto-generated catch block
				StackTracePrinter.print(e2);
			}
		}
	}

	public JList getEventList() {
		return listEvents;
	}

	public JList getListBirthday() {
		return listBirthday;
	}

	public void resetEventsBox() {
		lblWarning.setVisible(false);
		dateChooserFrom.setDate(null);
		dateChooserTo.setDate(null);
	}
}


